package com.xy.exam.security;


import com.xy.exam.Exception.ServiceException;
import com.xy.exam.dao.mapper.UserMapper;
import com.xy.exam.pojo.vo.UserLoginInfoVO;
import com.xy.exam.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security自动调用了loadUserByUsername()方法,参数{}", s);
        // 假设正确的用户名是root，匹配的密码是1234
        UserLoginInfoVO loginInfo = userMapper.getLoginInfoByUsername(s);
        log.debug("logininfo:{}",loginInfo);
        if (loginInfo==null) {
            log.debug("根据用户名【{}】查询登录信息，结果：{}", loginInfo);
//            String message = "用户名【{}】错误，将不会返回有效的UserDetails（用户详情）";
//            log.warn(message);
            String message = "登陆失败，用户名不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        log.debug("开始创建返回给Spring Security的UserDetails对象……");
    /*   UserDetails userDetails = User.builder() // 构建者模式
                .username(loginInfo.getUsername()) // 存入用户名
                .password(loginInfo.getPassword()) // 存入密码
                .disabled(loginInfo.getEnable() != 1) // 存入启用、禁用状态
                .accountLocked(false) // 存入账号是否锁定的状态
                .credentialsExpired(false) // 存入凭证是否过期的状态
                .accountExpired(false) // 存入账号是否过期的状态
                .authorities("这是一个临时的山寨权限，暂时没什么用") // 存入权限列表
                .build(); // 执行构建，得到UserDetails类型的对象*/
//        authorities.add(new SimpleGrantedAuthority("这是一个临时的山寨权限，暂时没什么用"));

        /*该项目目前没有权限功能,但预留了权限代码位置*/

        Collection<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("这是一个临时的山寨权限，暂时没什么用"));
/*        for (String permission : loginInfo.getPermissions()) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }*/

        AdminDetails adminDetails = new AdminDetails(
                loginInfo.getId(),
                loginInfo.getUsername(),
                loginInfo.getPassword(),
                loginInfo.getEnable() == 1,
                authorities
        );
        log.debug("即将向Spring Security返回UserDetails类型的对象，返回结果：{}", adminDetails);
        return adminDetails;
    }

}
